package baseclass.d_list;

import java.util.Iterator;
import java.util.LinkedList;

/**
 * @date 2020/2/28 20:54
 */
public class LRUCache<K,V> {
    static class Node<K,V>{
        K k;
        V v;
        public Node(K k, V v) {
            this.k = k;
            this.v = v;
        }
    }
    private LinkedList<Node<K,V>> cache;

    private int capacity;

    public LRUCache(int capacity) {
        this.capacity = capacity;
        this.cache = new LinkedList<>();
    }

    public void put(K k,V v){
        //否则看是否已经包含K，如果包含，删除K并返回V，否则返回null
        hasKey(k);
        //如果链表满了，那么就删除最后1个，新增到头部
        if(cache.size() >= capacity){
            cache.removeLast();
        }
        //直接插入头部
        cache.addFirst(new Node<>(k,v));

    }
    public V get(K k){
        //遍历查看是否有K
        V res;
        if((res = hasKey(k)) == null){
            //说明不含有K
            return null;
        }
        cache.addFirst(new Node<>(k,res));
        return res;
    }

    public V remove(K k){
        //如果有K则移除，并返回非null
        return hasKey(k);
    }

    /**
     * 查看cache的Node是否含有K，若有则移除
     */
    private V hasKey(K k){
        Iterator<Node<K, V>> iterator = cache.iterator();
        while (iterator.hasNext()){
            Node<K, V> node = iterator.next();
            //TODO 这里可以优化判断相等的条件
            if(node.k == k){
                iterator.remove();
                return node.v;
            }
        }
        return null;
    }

    @Override
    public String toString() {
        StringBuffer sb = new StringBuffer();
        Iterator<Node<K, V>> iterator = cache.iterator();
        while (iterator.hasNext()){
            Node node = iterator.next();
            sb.append("K：").append(node.k).append("  V:").append(node.v).append("\r\n");
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        LRUCache<Integer, String> cache = new LRUCache<>(5);
        for (int i = 1; i <= 5; i++) {
            cache.put(i," "+i);
            System.out.println(cache);
        }
        System.out.println("插入6");
        cache.put(6," "+6);
        System.out.println(cache);
        System.out.println("查询5");
        System.out.println(cache.get(5));
        System.out.println(cache);
        System.out.println("删除2");
        System.out.println(cache.remove(2));
        System.out.println(cache);
        System.out.println("插入2");
        cache.put(2,"2");
        System.out.println(cache);
        System.out.println("查询3");
        System.out.println(cache.get(3));
        System.out.println(cache);
    }

}
